//
//  XuanKeVC.m
//  ZhiBoYuan
//
//  Created by apple on 2018/4/20.
//  Copyright © 2018年 apple. All rights reserved.
//

#import "XuanKeVC.h"
//#import "TeachCell.h"

#import "XuanKeCell.h"
static NSString *ident = @"XuanKeCell";

#import "QuXuanKeVC.h"

#import "TongJIFenXiVC.h"

#import "AdetailViewController.h"


@interface XuanKeVC ()
<
UITableViewDelegate,
UITableViewDataSource
>
@property (nonatomic, strong) NSMutableArray *dataArray;
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, assign) NSInteger pageIndex;
@end

@implementation XuanKeVC

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    
    self.title = @"选课";
    
    self.view.backgroundColor =[UIColor whiteColor];
    
    [self.view addSubview:self.tableView];
    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:@"去选课" style:(UIBarButtonItemStyleDone) target:self action:@selector(open)];
    [self getdate];
    
}

-(void)setTask:(Task *)task{
    _task = task;
}

-(void)viewDidDisappear:(BOOL)animated{
    [super viewDidDisappear:animated];
    
    _task.course_count = [NSString stringWithFormat:@"%zd",self.dataArray.count];
    
    
    self.fresh(_task);
}


-(void)getdate{
    SGParameter *parameter  = [[SGParameter alloc] init];
    
    parameter.body = @{@"task_id":self.teskID };
    
    NSString *lastUrl  = @"g=Client&m=Task&a=courseList";
    __weak __typeof(&*self)weakSelf = self;
    [SGHttpTool POST:[NSString stringWithFormat:@"%@%@",HTTPP,lastUrl] parameter:parameter sucess:^(id responseObject) {
        
        
        [weakSelf.tableView.mj_header endRefreshing];
        
        [weakSelf.tableView.mj_footer endRefreshing];
        
        NSDictionary *dic = responseObject;
        
        
        if (_pageIndex == 1) {
            [self.dataArray removeAllObjects];
        }
        
        for (NSDictionary *dicc in dic[@"data"][@"course_list"]) {
            [self.dataArray addObject:dicc];
        }
        
//        self.dataArray = dic[@"data"][@"course_list"];
        
        NSLog(@"%@",dic);
        
        [self.tableView reloadData];
        
        
        
    } failure:^(NSError *error) {
        NSLog(@"%@",error);
        
    }];
}


- (void)open {
    NSLog(@"添加");
    
    QuXuanKeVC *vc = [[QuXuanKeVC alloc]init];
    
    
    vc.teskID = self.teskID;
    
     __weak __typeof(&*self)weakSelf = self;
    vc.blockAdd = ^(id arr) {
        self.pageIndex =1;
        
         [weakSelf getdate];
        
////        [self.dataArray addObject:@"1"];
//        [_tableView reloadData];
        
    };

    [self.navigationController pushViewController:vc animated:YES];
}
-(NSMutableArray *)dataArray{
    if (!_dataArray) {
        _dataArray = [NSMutableArray array];
    }
    return _dataArray;
}


- (UITableView *)tableView {
    if (!_tableView) {
        UITableView *  tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, NAVIGATION_BAR_HEIGHT, ScreenWidth, Screenheight- NAVIGATION_BAR_HEIGHT) style:UITableViewStylePlain];
        tableView.backgroundColor = [UIColor clearColor];
        tableView.delegate        = self;
        tableView.dataSource      = self;
        tableView.separatorStyle=UITableViewCellSeparatorStyleNone;
        
        tableView.estimatedRowHeight = 44.0f;//推测高度，必须有，可以随便写多少
        
        tableView.rowHeight = UITableViewAutomaticDimension;//iOS8之后默认就是这个值，可以省略
        
        
        tableView.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
        
        //        self.extendedLayoutIncludesOpaqueBars = YES;
        
        if (@available(iOS 11.0, *)) {
            tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
        } else {
            self.automaticallyAdjustsScrollViewInsets = NO;
        }
//        tableView.contentInset = UIEdgeInsetsMake(0, 0, 49, 0);
//        tableView.scrollIndicatorInsets = _tableView.contentInset;
//
        
        [tableView registerNib:[UINib nibWithNibName:ident bundle:nil] forCellReuseIdentifier:ident];
        
        //        [tableView registerClass:[WoTableViewCell class] forCellReuseIdentifier:identfire];
        //        [tableView registerClass:[WoHeaderCell class] forCellReuseIdentifier:identHead];
        
        
        [tableView setTableFooterView:[[UIView alloc] initWithFrame:CGRectZero]];
        __weak __typeof(&*self)weakSelf = self;
        
        // 下拉刷新
        tableView.mj_header= [MJRefreshNormalHeader headerWithRefreshingBlock:^{

            weakSelf.pageIndex = 1;

            [weakSelf getdate];


        }];
//
//        //         上拉加载
//        tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
//
//            if ( weakSelf.pageIndex < -1 ) {  weakSelf.pageIndex = 1;  }
//
//            [weakSelf getdate];
////            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
////                [weakSelf.tableView.mj_footer endRefreshing];
////            });
//        }];
        _tableView = tableView;
        
    }
    return _tableView;
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.dataArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    XuanKeCell *cell = [tableView dequeueReusableCellWithIdentifier:ident forIndexPath:indexPath];
    
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.backgroundColor = [UIColor clearColor];
    
    Course *c = [[Course alloc]initWithDictionary:self.dataArray[indexPath.row]];
    
    cell.tittleLabel.text = c.name;
    
    [cell.bigIMage sd_setImageWithURL:[NSURL URLWithString:c.image_url] placeholderImage:PlaceHoldImage];
    
    
    BTN_MSG_FUNC(cell.delButton, delSender:);
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tpngjiSender:)];
    
    cell.typlealbel.userInteractionEnabled = YES;
    
    [cell.typlealbel addGestureRecognizer:tap];
    
    cell.typlealbel.font = [UIFont systemFontOfSize:15];
    
    cell.typlealbel.edgeInsets = UIEdgeInsetsMake(5, 5, 5, 5);
    

    
    return cell;
}

#pragma mark ----------------------- 查看统计圆饼图  ------------------------
- (void)tpngjiSender:(UITapGestureRecognizer *)tap{
    
        NSIndexPath *myIndex=[self.tableView indexPathForCell:(XuanKeCell*)[[tap.view superview]superview]];
    
    NSLog(@"%zd",myIndex.row);
    
    TongJIFenXiVC *vc =[[TongJIFenXiVC alloc]init];
    vc.task_id = self.teskID;
//    Course *c = [[Course alloc]initWithDictionary:self.dataArray[indexPath.row]];
    vc.course_id = [self.dataArray[myIndex.row] valueForKey:@"id"];
    vc.isComeFormTi = NO;
    [self.navigationController pushViewController:vc animated:YES];
    
    
}

#pragma mark ----------------------- 删除 ------------------------
-(void)delSender:(UIButton *)sender{
    
    NSIndexPath *myIndex=[self.tableView indexPathForCell:(XuanKeCell*)[[sender superview]superview]];
    //如果按钮是加在cell上的contentView上
    NSLog(@"myIndex.section==%ld",myIndex.section);
    NSLog(@"myIndex.row==%ld",myIndex.row);
    
    NSLog(@"删除课程");
    
//    NSLog(@"%@",self.dataArray[myIndex.row]);
//
//    [self.dataArray removeObject:self.dataArray[myIndex.row]];

    
    SGParameter *parameter  = [[SGParameter alloc] init];
    
//    NSMutableArray *arr = self.dataArray;
    
//    Course *c = [[Course alloc]initWithDictionary:arr[myIndex.row]];
    Course *c = [[Course alloc]initWithDictionary:self.dataArray[myIndex.row]];
    
    
    parameter.body = @{@"task_id":self.teskID,
                       @"course_id":c.id };
    NSString *lastUrl  = @"g=Client&m=Task&a=removeCourse";
    __weak __typeof(&*self)weakSelf = self;
    [SGHttpTool POST:[NSString stringWithFormat:@"%@%@",HTTPP,lastUrl] parameter:parameter sucess:^(id responseObject) {
        
        NSDictionary *dic = responseObject;
        
        NSString *status = dic[@"status"];
        NNSLog(@"dic  = %@",dic);

        if ([status integerValue] == 200)
        {
            
            NNSLog(@"%zd",weakSelf.dataArray.count);
            
            NNSLog(@"%zd",myIndex.row);
            
            [weakSelf.dataArray removeObjectAtIndex:myIndex.row];
            [self.tableView deleteRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:myIndex.row inSection:0]] withRowAnimation:UITableViewRowAnimationTop];
//            [self.tableView reloadData];
//            [weakSelf getdate];

        }else{
            [MBProgressHUD showTextOnly:weakSelf.view message:dic[@"msg"] delay:3];
        }
 
    } failure:^(NSError *error) {
        NSLog(@"%@",error);
        
    }];
}


-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    
    NSLog(@"1231313%zd",indexPath.row);
//    AdetailViewController *VC= [[AdetailViewController alloc]init];
//
//     Course *c = [[Course alloc]initWithDictionary:self.dataArray[indexPath.row]];

//    VC.course_id = c.id;
//
//    [self.navigationController pushViewController:VC animated:YES];
    
    Course *c = [[Course alloc]initWithDictionary:self.dataArray[indexPath.row]];
     [Helper keChengDetailFromVC:self course_id:c.id];
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
